package com.bjpowernode.crm.web.advice;

import com.bjpowernode.crm.exception.RepeatException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@ControllerAdvice
public class MyExceptionHandler {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @ExceptionHandler(RepeatException.class)
    public void repeatException(Exception e, HttpServletResponse response, HttpServletRequest request) throws Exception {
        exception(e, response, request);
    }

    @ExceptionHandler(Exception.class)
    public void exception(Exception e, HttpServletResponse response, HttpServletRequest request) throws Exception {
        e.printStackTrace();
        // ajax请求会携带请求头：X-Requested-With，注意，这种仅当使用jQuery框架时才是必然满足，其它框架不一定
        if(request.getHeader("X-Requested-With") != null) {

            // 以ajax形式进行响应


            String json = MAPPER.writeValueAsString(new HashMap(){{
                put("success", false);
                put("msg", e.getMessage());
            }});

            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);

            return;
        }

        // 针对传统请求的响应
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("<script>alert('"+e.getMessage()+"');history.back();</script>");
    }
}
